package com.gurumades.jsonform.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.gurumades.jsonform.shared.dispatch.JsonHelper;

@SuppressWarnings({ "unused", "rawtypes" })
public class JSONUtils extends JsonHelper {

	public static String getString(String key, JSONObject o) {
		
		return getString(key, o, null);
	}

	public static String getString(String key, JSONObject o, String def) {

		if (o.containsKey(key) && o.get(key).isString() != null) {
			return o.get(key).isString().stringValue();
		}
		return def;
	}

	public static boolean getBoolean(String key, JSONObject o) {
		return getBoolean(key, o, false);
	}

	@Override
	public Map wrapItem(Object jsonImpl) {
		JSONObject val = (JSONObject) jsonImpl;

		return toMap(val);
	}

	@SuppressWarnings("unchecked")
	public static Map toMap(JSONObject val) {
		Map map = new HashMap();

		Set<String> keys = val.keySet();

		for (String string : keys) {
			JSONValue line = val.get(string);
			if (line.isString() != null) {
				map.put(string, line.isString().stringValue());
			} else if (line.isBoolean() != null) {
				map.put(string, line.isBoolean().booleanValue());
			} else if (line.isNumber() != null) {
				map.put(string, line.isNumber().doubleValue());
			} else if (line.isNull() != null) {
				map.put(string, null);
			} else if (line.isObject() != null) {
				JSONObject o = line.isObject();
				Map tmp = toMap(o);
				map.put(string, tmp);
			} else if (line.isArray() != null) {
				JSONArray o = line.isArray();
				ArrayList tmp = toArray(o);
				map.put(string, tmp);
			}
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public static ArrayList toArray(JSONArray val) {
		ArrayList list = new ArrayList();

		for (int i = 0; i < val.size(); i++) {
			JSONValue line = val.get(i);
			if (line.isString() != null) {
				list.add(i, line.isString().stringValue());
			} else if (line.isBoolean() != null) {
				list.add(i, line.isBoolean().booleanValue());
			} else if (line.isNumber() != null) {
				list.add(i, line.isNumber().doubleValue());
			} else if (line.isNull() != null) {
				list.add(i, null);
			} else if (line.isObject() != null) {
				JSONObject o = line.isObject();
				Map tmp = toMap(o);
				list.add(i, tmp);
			} else if (line.isArray() != null) {
				JSONArray o = line.isArray();
				ArrayList tmp = toArray(o);
				list.add(i, tmp);
			}
		}

		return list;
	}

	public static boolean getBoolean(String key, JSONObject o, boolean def) {
		if (o.containsKey(key) && o.get(key).isBoolean() != null) {
			return o.get(key).isBoolean().booleanValue();
		}
		return def;
	}
}
